<?php
declare(strict_types=1);

namespace app\controller;

use support\Response;
use support\Redis;
use hg\apidoc\annotation as Apidoc;

/**
 * UDP 统计控制器
 * 
 * @Apidoc\Title("UDP 统计")
 * @Apidoc\Desc("获取UDP服务运行状态和统计信息")
 * @Apidoc\Group("UDP")
 * @Apidoc\Sort(999)
 */
class UdpStatsController
{
    /**
     * @Apidoc\Title("UDP统计信息")
     * @Apidoc\Desc("获取UDP服务的运行状态、接收包数量、最后接收时间等统计信息")
     * @Apidoc\Url("/udp/stats")
     * @Apidoc\Method("GET")
     * @Apidoc\Tag("监控")
     * @Apidoc\Tag("统计")
     * @Apidoc\Param("无参数", type="none", desc="此接口无需参数")
     * @Apidoc\Returned("udp_port", type="int", desc="UDP监听端口")
     * @Apidoc\Returned("recv_packets", type="int", desc="接收到的数据包总数")
     * @Apidoc\Returned("last_packet_at", type="string", desc="最后接收数据包的时间")
     * @Apidoc\Returned("decode_errors", type="int", desc="解码错误数量")
     * @Apidoc\Returned("redis_available", type="bool", desc="Redis连接是否可用")
     * @Apidoc\Returned("message", type="string", desc="错误信息（仅当Redis不可用时返回）", require=false)
     * @Apidoc\ResponseStatus({
     *     {"code": 200, "desc": "请求成功"}
     * })
     * 
     * @return Response
     */
    public function stats(): Response
    {
        // Redis 不可用时降级返回，避免 500
        try {
            $recvPackets = (int)(Redis::get('jt808:recv_packets') ?? 0);
            $lastPacketAt = (string)(Redis::get('jt808:last_packet_at') ?? '');
            $decodeErrors = (int)(Redis::get('jt808:decode_errors') ?? 0);
        } catch (\Throwable $e) {
            return json([
                'udp_port' => (int)env('UDP_PORT', 8808),
                'recv_packets' => 0,
                'last_packet_at' => '',
                'decode_errors' => 0,
                'redis_available' => false,
                'message' => $e->getMessage(),
            ]);
        }

        $stats = [
            'udp_port' => (int)env('UDP_PORT', 8808),
            'recv_packets' => $recvPackets,
            'last_packet_at' => $lastPacketAt,
            'decode_errors' => $decodeErrors,
            'redis_available' => true,
        ];
        return json($stats);
    }
}